package models.connection;

import de.puc.defencetower.model.Map;
import de.puc.defencetower.model.Monster;
import de.puc.defencetower.model.Tower;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import play.api.templates.Html;
import play.libs.Json;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: chlemke
 * Date: 17.01.14
 * Time: 22:40
 * send only the changes
 */
public  class GameUpdate {


    final Map map;

    public GameUpdate(Map map) {
        this.map = map;
    }

    public ObjectNode getJson(){


        ObjectNode event = Json.newObject();
        event.put("kind", "GameUpdate");

        ArrayNode jsonUpdateNodes = JsonNodeFactory.instance.arrayNode();

        // monsters
        List<Monster> monsters = map.getMonsters();
        for(Monster m : monsters ){

            ObjectNode monsterNode = JsonNodeFactory.instance.objectNode();
            monsterNode.put("x", m.getCurrentMapCell().getMapPos().getX());
            monsterNode.put("y", m.getCurrentMapCell().getMapPos().getY());
            monsterNode.put("html", views.html.mapelements.monster.render(m).toString());
            jsonUpdateNodes.add(monsterNode);
        }

        // towers
        List<Tower> towers = map.getTowers();
        for(Tower t : towers ){

            ObjectNode towerNode = JsonNodeFactory.instance.objectNode();
            towerNode.put("x", t.getCurrentMapCell().getMapPos().getX());
            towerNode.put("y", t.getCurrentMapCell().getMapPos().getY());
            towerNode.put("html", views.html.mapelements.tower.render(t).toString());
            jsonUpdateNodes.add(towerNode);
        }

        event.put("updatesarray", jsonUpdateNodes);
        event.put("gameover", map.isGameOver());
        event.put("monster", map.getDeadMonsterNumber());
        event.put("gold", map.getGold());
        event.put("wave", map.getMonstersSpawned());
        event.put("live", map.getLive());
        event.put("secondstospawn", map.getSecondsToNextSpawn().getSeconds());

        return event;
    }
}